package com.exam.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.exam.exception.CommonErrorCode;
import com.exam.exception.RestErrorResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyAuthenticationEntryPointHandler implements AuthenticationEntryPoint {

    /**
     * 开始认证过程
     *
     * @param request HTTP请求对象
     * @param response HTTP响应对象
     * @param authenticationException 认证异常对象
     * @throws IOException 当响应输出流无法写入时抛出
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException {
        // 设置响应的内容类型为JSON，并指定字符集为UTF-8
        response.setContentType("application/json;charset=UTF-8");
        // 设置响应的状态码为401，表示未授权
        response.setStatus(401);

        // 创建一个RestErrorResponse对象，包含错误码和错误信息
        RestErrorResponse apiError = new RestErrorResponse(String.valueOf(CommonErrorCode.UNAUTHORIZED.getCode()), authenticationException.getMessage());

        // 创建一个ObjectMapper对象，用于将Java对象转换为JSON字符串
        ObjectMapper objectMapper = new ObjectMapper();

        // 使用响应的输出流写入JSON字符串
        response.getWriter().write(objectMapper.writeValueAsString(apiError));
    }
}
